package com.jd.risk.bankorder.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wycds.datacenter.api.DataReadService;
import com.wycds.datacenter.api.pojo.HbaseQueryResult;

@Service(value="hbaseQueryUtil")
public class HbaseQueryUtil {
	
	static Logger logger = LoggerFactory.getLogger(HbaseQueryUtil.class);

	public static void installParamsAnd(StringBuffer params,String paramName,String compare,String value,boolean isSha256,boolean isBracketFront,boolean isBracketAfter){
		if(CommonUtil.isNotEmpty(value)){
			params.append(" and ");
			installParams(params,paramName,compare,value,isSha256,isBracketFront,isBracketAfter);
		}
	}

	public static void installParamsOr(StringBuffer params,String paramName,String compare,String value,boolean isSha256,boolean isBracketFront,boolean isBracketAfter){
		if(CommonUtil.isNotEmpty(value)){
			params.append(" or ");
			installParams(params,paramName,compare,value,isSha256,isBracketFront,isBracketAfter);
		}
	}

	private static void installParams(StringBuffer params,String paramName,String compare,String value,boolean isSha256,boolean isBracketFront,boolean isBracketAfter){
		if(isBracketFront)
			params.append("(");
		params.append(paramName);
		params.append(compare);
		params.append("'");
		params.append(isSha256?encryptSHA256(value):value);
		params.append("'");
		if(isBracketAfter)
			params.append(")");
	}

	public static List<Map<String, String>> execHbaseQueryList(StringBuffer querySql,DataReadService dataReadService){
		String sql = querySql.toString();
		logger.info("query sql:"+sql);
		try {
			HbaseQueryResult hqr = dataReadService.read(sql);
			return hqr.getResult()==null?new ArrayList<Map<String,String>>():hqr.getResult();
		} catch (Exception e) {
			logger.error("",e);
			return new ArrayList<Map<String,String>>();
		}
	}

	public static Map<String, String> execHbaseQueryObject(StringBuffer querySql,DataReadService dataReadService){
		List<Map<String, String>> result = execHbaseQueryList(querySql, dataReadService);
		if(result!=null&&!result.isEmpty())
			return result.get(0);
		return null;
	}

	public static Map<String, String> execHbaseQueryObject(Map<String,String> param,DataReadService dataReadService){
		param.put("limitStartEnd"," limit 0,1");
		List<Map<String,String>> result = queryTradeInfo(param, dataReadService);
		if(result!=null&&!result.isEmpty())
			return result.get(0);
		return null;
	}

	public static List<Map<String, String>> queryTradeInfo(Map<String,String> param,DataReadService dataReadService){
		StringBuffer querySql = new StringBuffer();
		querySql.append("select * from wyrisk.trade_base_operate where primary_key is not null");
		installParamsAnd(querySql,"created_date",">", CommonUtil.getDateFormat(CommonUtil.getFormatCommonForHbase(), CommonUtil.getFormatCommon(),param.get("startTime")),false,false,false);
		installParamsAnd(querySql,"created_date","<", CommonUtil.getDateFormat(CommonUtil.getFormatCommonForHbase(), CommonUtil.getFormatCommon(),param.get("endTime")),false,false,false);
		installParamsAnd(querySql,"payment_code","=",param.get("paymentCode"),false,false,false);
		installParamsAnd(querySql,"sub_trade_type_code","=",param.get("subTradeTypeCode"),false,false,false);
		installParamsAnd(querySql,"trade_type_code","=",param.get("tradeTypeCode"),false,false,false);
		if(CommonUtil.isNotEmpty(param.get("customCondition")))
			querySql.append(param.get("customCondition"));
		installParamsAnd(querySql,"new_member_id","=",param.get("newMemberId"),false,false,false);
		installParamsAnd(querySql,"primary_key","=",param.get("primaryKey"),false,false,false);
		installParamsAnd(querySql,"jd_pin","=",param.get("jdPin"),false,false,false);
		installParamsAnd(querySql,"seller_merchant_no","=",param.get("sellerMerchantNo"),false,false,false);
		installParamsAnd(querySql,"imei","=",param.get("imei"),false,false,false);
		installParamsAnd(querySql,"risk_id","=",param.get("riskId"),false,false,false);
		installParamsAnd(querySql,"idfv","=",param.get("idfv"),false,false,false);
		installParamsAnd(querySql,"eid","=",param.get("eid"),false,false,false);
		String emailType = param.get("emailType");
		if("0".equals(emailType)){
			installParamsAnd(querySql,"email1","=",param.get("email"),false,true,false);
			installParamsOr(querySql,"email2","=",param.get("email"),false,false,true);
		}else if("1".equals(emailType)){
			installParamsAnd(querySql,"email2","=",param.get("email"),false,false,false);
		}else if("2".equals(emailType)){
			installParamsAnd(querySql,"email1","=",param.get("email"),false,false,false);
		}
		installParamsAnd(querySql,"mac1","=",param.get("mac"),false,false,false);
		installParamsAnd(querySql,"ip1","=",param.get("ip"),false,false,false);
		installParamsAnd(querySql,"holder_id_number","=",param.get("idNo"),false,false,false);
		installParamsAnd(querySql,"card_pan","=",param.get("cardPan"),true,false,false);
		installParamsAnd(querySql,"card_pan","=",param.get("cardBankCode"),false,false,false);
		installParamsAnd(querySql,"trade_pay_request_no","=",param.get("tradePayRequestNo"),false,false,false);
		String phoneType = param.get("phoneType");
		if("0".equals(phoneType)){
			installParamsAnd(querySql,"mobile1","=",param.get("phone"),false,true,false);
			installParamsOr(querySql,"mobile2","=",param.get("phone"),false,false,true);
		}else if("1".equals(phoneType)){
			installParamsAnd(querySql,"mobile1","=",param.get("phone"),false,false,false);
		}else if("2".equals(phoneType)){
			installParamsAnd(querySql,"mobile2","=",param.get("phone"),false,false,false);
		}
		installParamsAnd(querySql,"merchant_trade_no","=",param.get("merchantTradeNo"),false,false,false);
		installParamsAnd(querySql,"trade_no","=",param.get("tradeNo"),false,false,false);
		installParamsAnd(querySql,"bank_no","=",param.get("bankOrderNo"),false,false,false);
		if(param.get("orderBy")!=null){
			querySql.append(param.get("orderBy"));
		}else
			querySql.append(" order by created_date desc");
		if(param.get("limitStartEnd")!=null){
			querySql.append(param.get("limitStartEnd"));
		}else{
			querySql.append(" limit 0,100");
		}
		List<Map<String, String>> results = execHbaseQueryList(querySql,dataReadService);
		return results;
	}


	public static String encryptSHA256(String orginanlValue)  {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
			messageDigest.reset();
			messageDigest.update(orginanlValue.getBytes("UTF-8"));
		} catch (Exception e) {
			logger.error("NoSuchAlgorithmException caught!");
		}
		byte[] byteArray = messageDigest.digest();

		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			int v = byteArray[i] & 0xff;
			if (v < 16) {
				buffer.append(0);
			}
			buffer.append(Integer.toHexString(v));
		}
		logger.debug("encrypted value =" + buffer);
		return buffer.toString();

	}
}
